package com.gid.rcflightlogger;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;

import com.orm.androrm.Filter;

public class BatteryEditActivity extends BaseActivity {
	//db objects
	private Battery mBattery = null;
	private Cycle mCycle = null;
	
	public static final int INVALID_ID = 0;
	private int mID = INVALID_ID;
	
	//batt names/tags for auto complete
	String[] mExistingBatteryNames; 
	String[] mExistingBatteryTags;
	
	//form objects
	private AutoCompleteTextView mName;
	private AutoCompleteTextView mTag;
	private Spinner mType;
	private EditText mPurchaseDate;
	private EditText mCost;
	private EditText mExistingCycles;
	private EditText mExistingRuntimeMinutes;
	private CheckBox mStatus;
	private Button mSave;
	private Button mDelete; 
	
	//dialog ids
	public static final int DIALOGID_PURCHASEDATE = 1;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_batteryedit);
    	
        mName = (AutoCompleteTextView) findViewById(R.id.batteryedit_input_name);
        mTag = (AutoCompleteTextView) findViewById(R.id.batteryedit_input_tag);
        mType = (Spinner) findViewById(R.id.batteryedit_spinner_type);
        mPurchaseDate = (EditText) findViewById(R.id.batteryedit_input_purchasedate);
        mCost = (EditText) findViewById(R.id.batteryedit_input_cost);
        mExistingCycles = (EditText) findViewById(R.id.batteryedit_input_cycles);
        mExistingRuntimeMinutes = (EditText) findViewById(R.id.batteryedit_input_runtimemins);
        mStatus = (CheckBox) findViewById(R.id.batteryedit_input_status);
        mSave = (Button) findViewById(R.id.batteryedit_btn_save);
        mDelete = (Button) findViewById(R.id.batteryedit_btn_delete);
       
        mType.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, Battery.TYPE_ARRAY));

        //check if we are doing an add or edit
        if (savedInstanceState != null)
        {
        	mID = savedInstanceState.getInt(Battery.ID_LABEL, INVALID_ID);
        }
        
        if (mID == INVALID_ID) {
        	mID = getIntent().getIntExtra(Battery.ID_LABEL, INVALID_ID);
        }
        
        
        //by this stage, invalid mID means we are creating a new entry
        if (mID == INVALID_ID)
        {
        	//add Battery
        	mBattery = new Battery();
        	mCycle = new Cycle();
        	mCycle.setFake(true);
        	mCycle.setCount(0);
        	mCycle.setBattery(mBattery);
        	mSave.setText(" Add ");
        	mSave.setVisibility(View.VISIBLE);
        	this.setTitle("Adding New Battery");
        }
        else
        {	
        	//edit existing one
        	this.setTitle("Updating Battery");
        	mBattery = Battery.objects(getApplicationContext()).get(mID);
        	if (mBattery == null)
        	{
        		//error condition
        		setResult(RESULT_FIRST_USER);
        		finish();
        	}
        	Filter filter = new Filter();
        	filter.is("mBattery", mBattery).is("mFake", 1);
        	List<Cycle> fcs = Cycle.objects(getApplicationContext()).filter(filter).toList();
        	if (!fcs.isEmpty())
        	{
        		mCycle = fcs.get(0);
        	}
        	else
        	{
        		mCycle = new Cycle();
            	mCycle.setFake(true);
            	mCycle.setCount(0);
            	mCycle.setBattery(mBattery);
        	}
        	mSave.setText("Update");
        	mSave.setVisibility(View.VISIBLE);
        	
        	mDelete.setVisibility(View.VISIBLE);
        	mDelete.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					AlertDialog.Builder builder = new AlertDialog.Builder(BatteryEditActivity.this);
					builder.setMessage("Delete this battery?").setCancelable(false);
					builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							mBattery.delete(getApplicationContext());
							setResult(RESULT_OK);
			        		finish();
						}
					});
					builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
	        	    AlertDialog alert = builder.create();
	        	    alert.show();
				}
			});
        }
        
        //Register listeners  
        //1- trigger date picker dialog on date field, need both touch event and key event for keyboard and touch UI      
        mPurchaseDate.setOnTouchListener(new EditText.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent e) {
				showDialog(DIALOGID_PURCHASEDATE);
				return true;
			}
        });
        mPurchaseDate.setOnKeyListener(new View.OnKeyListener(){

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				showDialog(DIALOGID_PURCHASEDATE);
				return true;
			}
        	
        });
        
        //2- trigger db save on button
        mSave.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (saveData())
					setResult(RESULT_FIRST_USER);
				else
					setResult(RESULT_OK);
				finish();
			}
		});
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog diag;
		switch (id) {
		case DIALOGID_PURCHASEDATE:
			Date date = myUtils.Str2Date(mPurchaseDate.getText().toString());
			//myUtils.makeToast(getApplicationContext(), "date string = " + mBuildDate.getText().toString()); 
			diag = new DatePickerDialog(this, mDateSetListener, date.getYear() + 1900, date.getMonth(), date.getDate());
			return diag;
		default:
			return super.onCreateDialog(id);
		} 
	}
	
	//the callback received when the user "sets" the time in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mPurchaseDate.setText(myUtils.Date2Str(year, monthOfYear, dayOfMonth));
		}
	};
        
    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }
	
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mID != INVALID_ID)
        	outState.putInt(Battery.ID_LABEL, mID);
    }
    
    //load data from mBattery object into form
	private void loadData() {
		mName.setText(mBattery.getName());
		mTag.setText(mBattery.getTag());
		String type = mBattery.getType();
		for (int i = 0; i< Battery.TYPE_ARRAY.length; i++)
		{
			if (Battery.TYPE_ARRAY[i].equals(type))
			{
				mType.setSelection(i);
				break;
			}
		}

		mPurchaseDate.setText(myUtils.Date2Str(mBattery.getPurchaseDate()));
		mCost.setText(Double.toString(mBattery.getCost()));
		mExistingCycles.setText(Integer.toString(mCycle.getCount()));
		mExistingRuntimeMinutes.setText(Integer.toString(mCycle.getDuration()/60));
		mStatus.setChecked(mBattery.getStatus());
		
		Set<String> names = new HashSet<String>();
		Set<String> tags = new HashSet<String>();
		List<Battery> all = Battery.objects(this).all().orderBy("-mName").toList();
		for (Battery b : all)
		{
			names.add(b.getName());
			tags.add(b.getTag());
			Log.i(LOG_TAG, "battery: " + b.getName() + " - " + b.getTag());
		}
		
		if (!names.isEmpty())
		{
			mExistingBatteryNames = (String[]) names.toArray(new String[names.size()]);
			mExistingBatteryTags = (String[]) tags.toArray(new String[tags.size()]);
			mName.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, mExistingBatteryNames));
			mTag.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, mExistingBatteryTags));
		}
	}
	
	//save data from form into database
	private boolean saveData() 
	{
		mBattery.setName(mName.getText().toString());
		mBattery.setTag(mTag.getText().toString());
		mBattery.setType((String)mType.getSelectedItem());
		mBattery.setPurchaseDate(myUtils.Str2Date(mPurchaseDate.getText().toString()));
		
		double cost = 0.0;
		try
		{
			cost = Double.parseDouble(mCost.getText().toString());
		}
		catch (NumberFormatException e)
		{
			cost = 0.0;
		} 
		mBattery.setCost(cost);
		
		mBattery.setStatus(mStatus.isChecked());
		boolean bsave = mBattery.save(getApplicationContext());
		
		int cyclecount = 0;
		try
		{
			cyclecount = Integer.parseInt(mExistingCycles.getText().toString());
		}
		catch (NumberFormatException e)
		{
			cyclecount = 0;
		}
		mCycle.setCount(cyclecount);
		
		int runtime = 0;
		try
		{
			runtime = Integer.parseInt(mExistingRuntimeMinutes.getText().toString())*60;
		}
		catch (NumberFormatException e)
		{
			runtime = 0;
		}
		mCycle.setDuration(runtime); //we store flight duration in seconds in db
		
		mCycle.setBattery(mBattery);
		boolean csave = mCycle.save(getApplicationContext());
		//myUtils.makeToast(getApplicationContext(), "saved = " + mBattery.getId() + " " + mCycle.getId()); 
		return (bsave && csave);
	}
}
